/*
 * @Author: LiZn
 * @Date: 2021-08-21 06:15:35
 * @LastEditTime: 2021-08-22 23:53:40
 * @LastEditors: LiZn
 * @Description: file content
 * @FilePath: \todaynews\src\utils\request.js
 */
import Axios from 'axios'
import {Message} from 'element-ui'
import Vue from 'vue'
const axios = Axios.create({
  baseURL:process.env.VUE_APP_BASE_API,
  timeout:1000
})
// //请求拦截,有两个参数，一个是正确配置config,另一个是错误处理
axios.interceptors.request.use(config=>{
  //获取用户的token，判断用户有没有登录
  const userToken = localStorage.getItem('userToken');
  if(userToken){
    config.headers["Authorization"] = 'token '+userToken
  }
  return config
},error=>{
  //错误请求
  return Promise.reject(error)
});
//响应拦截
axios.interceptors.response.use(async response=>{
  const res = response.data;//获取返回的数据
  console.log(res)
  if(res.code==2){
    return res
  }else{
    if(res.code==203){
      //此时说明需要用户登录，
      Vue.prototype.$loginMes()
      return res
    }else{
      Message({
        message:res.message||'请求失败，请改正姿势',
        type:"error",
        duration:1000
      })
      return res
    }
  }
},error=>{
  Message({
    message:error.message,
    type:"error",
    duration:10000
  })
})
export default axios